/**
 * Created by Administrator on 2016/6/29.
 */
requirejs.config({
    baseUrl: 'js/',
    paths: {
        "jquery": ["/common/vendor/jquery-2.1.4/jquery-2.1.4.min"],
        "base": ["/common/scripts/base"],
        "ajax": ["/common/scripts/ajax"],
        "underscore": ["/common/vendor/underscore-1.8.3/underscore.min"],
        "chart": ["/common/charts/chart"],
        "file": ["/common/scripts/file"],
        "local": "/common/scripts/local",
        "popup": ["popup"],
    }
});

require(["jquery", "base", "ajax", "underscore", 'file', 'chart', 'local','popup'], function($, base, ajax, _, file, chart, local,popup) {
    var params = {
            DEFAULTSIZE: 45, //k线 默认数量
            MARKETNU: base.getUrlParameter('riseType') !== "1" ? "1A0001" : "2A01", // 上 1A0001 深 2A01
            DATEDOM: $('header .panel-body>dd:nth-of-type(2) span'),
            UPIMG: 'images/arrow-1.png',
            DOWNIMG: 'images/arrow-0.png',
            BTNACTIVE: '对比大盘',
            BTNTEXT: ' 收起大盘',
            CODE: base.getUrlParameter('stockCode'),
            NAME: decodeURIComponent(base.getUrlParameter('stockName')),
            MAKKETCODE: base.getUrlParameter('marketCode'),
            MAXSTART: base.getUrlParameter('startDate').replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'),
            MAXEND: base.getUrlParameter('endDate').replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'),
            MARKETCODE: base.getUrlParameter('marketCode'),
            CURRENCY: base.getUrlParameter('currency'),
            SOURCE: base.getUrlParameter('source'),
            URL: '/reqxml?action=27401&path=/account/hold_analysis/single_stock_explain?clientNo=($account)&token=($token)&stockCode=' + base.getUrlParameter('stockCode') + '&marketCode=' + base.getUrlParameter('marketCode'),
        },
        KChartOne = null,
        KChartTwo = null,
        kDateList1 = null,
        kDateList2 = null,
        STARTPOINT = 0,
        ENDPOINT = params.DEFAULTSIZE,
        _dataJson = null,
        _tabeJson = null,
        gbDataIndex = 0,
        clickTwoKIndex = 1;
    GBKStartDate = 0;
    var DATAK = [["20180206","0","0","0","0"],["20180207","6.490","5.910","5.870","6.540"],["20180208","5.940","5.890","5.820","6.090"],["20180209","5.690","5.550","5.450","5.690"],["20180212","5.650","5.520","5.510","5.710"],["20180213","5.600","5.620","5.590","5.770"],["20180214","5.620","5.680","5.570","5.730"],["20180215","5.750","5.820","5.750","5.920"],["20180220","5.820","5.780","5.700","5.860"],["20180221","5.780","6.000","5.760","6.030"],["20180222","5.950","5.980","5.840","6.070"],["20180223","6.060","6.040","6.010","6.140"],["20180226","6.150","5.990","5.960","6.170"],["20180227","6.060","5.880","5.800","6.110"],["20180228","5.760","5.710","5.650","5.820"],["20180301","5.640","5.770","5.610","5.800"],["20180302","5.640","5.530","5.530","5.680"],["20180305","5.550","5.480","5.470","5.630"],["20180306","5.590","5.670","5.450","5.670"],["20180307","5.630","5.570","5.530","5.780"],["20180308","5.600","5.580","5.540","5.640"],["20180309","5.640","5.590","5.570","5.660"],["20180312","5.680","5.720","5.600","5.740"],["20180313","5.730","5.760","5.710","5.870"],["20180314","5.680","5.720","5.650","5.740"],["20180315","5.680","5.680","5.630","5.700"],["20180316","5.610","5.550","5.550","5.660"],["20180319","5.550","5.530","5.510","5.630"],["20180320","5.540","5.520","5.490","5.570"],["20180321","5.600","5.530","5.520","5.670"],["20180322","5.590","5.520","5.510","5.660"],["20180323","5.400","5.390","5.310","5.420"],["20180326","5.390","5.350","5.270","5.400"],["20180327","5.440","5.480","5.430","5.540"],["20180328","5.420","5.380","5.380","5.490"],["20180329","5.430","5.360","5.300","5.450"],["20180403","5.340","5.490","5.340","5.510"],["20180404","5.500","5.370","5.360","5.520"],["20180406","5.420","5.360","5.330","5.460"],["20180409","5.440","5.360","5.330","5.440"],["20180410","5.360","5.510","5.360","5.570"],["20180411","5.550","5.650","5.530","5.730"],["20180412","5.700","5.630","5.540","5.700"]],
        dataKList = {
            min: 0,
            max: 32000,
            list: DATAK
        };
    var pageObj = {
        init: function() {
            TalkingData.onHTSCEvent("page", "leaf304", "持仓股综合分析_个股交易分析." + params.NAME, "", "");
            local.read({
                P_SOURCE: "", //系统源 150001 普通 150     002 信用  150003 限售股 150000 全账户
                P_CURRENCY: "", //401156 人民币 401344  港元 401840 美元
                P_DATETYPE: "", // 01 近一个月 03 近三个月 06 近六个月 00 自定义时间段
                P_MARKETTYPE: "", //市场类型 0 上证 1 深圳           
                P_STARTDATE: "", //开始时间
                P_ENDDATE: "", //结束时间
                P_DATELIST: "",
                P_ACCOUNT:'',
                P_CURRENCYTYPE:''
            }, function(_obj) {
                params.SOURCE = base.getUrlParameter('source');
                params.CURRENCY = base.getUrlParameter('currency');
                /*params.SOURCE = _obj.P_SOURCE;
                params.CURRENCY = _obj.P_CURRENCYTYPE;*/
                //alert(JSON.stringify(_obj));
                params.CURRENCYTEXT = _obj.P_CURRENCY;
                params.DATETYPE = _obj.P_DATETYPE;
                params.MAXSTART = _obj.P_STARTDATE.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');
                params.MAXEND = _obj.P_ENDDATE.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');
                params.URL = '/reqxml?action=27401&path=/account/hold_analysis/single_stock_explain?clientNo='+_obj.P_ACCOUNT+'&token=($token)&stockCode=' + base.getUrlParameter('stockCode') + '&marketCode=' + base.getUrlParameter('marketCode') + '&currency=' + params.CURRENCY + '&source=' + params.SOURCE;
                var tpNav = _.template($("#headerJson").html());
                $('header .panel-body .dropdown-menu').html(tpNav({
                    data: JSON.parse(_obj.P_DATELIST),
                }));
                $('header').css('visibility','visible');
                pageObj.readFile().then(function(obj) {
                    var _params = {};
                    if (obj) {
                        params.DATEDOM.html(obj.start.replace('20', '') + '-' + obj.end.replace('20', ''));
                        _params = {
                            dateType: '00',
                            startDate: obj.start.replace(/\//ig, ''),
                            endDate: obj.end.replace(/\//ig, '')
                        };
                        $('header .dropdown-menu li').eq(3).addClass('active');
                        params.MAXSTART = obj.start;
                        params.MAXEND = obj.end;
                    } else {
                        params.DATEDOM.html(params.MAXSTART.replace(/^\d{2}/g, '') + '-' + params.MAXEND.replace(/^\d{2}/g, ''));
                        var indexList = {
                            '01':0,
                            '03':1,
                            '06':2,
                            '00':3,
                        };
                        $('header .dropdown-menu li').eq(indexList[params.DATETYPE]).addClass('active');
                        _params = {
                            dateType: params.DATETYPE,
                            startDate: params.MAXSTART.replace(/\//g, ''),
                            endDate: params.MAXEND.replace(/\//g, '')
                        };
                    }
                    file.insert("positon.js", { startDate: null, endDate: null }, function(data) {
                        pageObj.getData(params.URL, _params).then(pageObj.innerDom);
                    });

                });
            });

            pageObj.pageEvent();
        },
        readFile: function() {
            var dtd = $.Deferred();
            file.getFileData("positon.js", function(data) {
                if (data.startDate && data.endDate) {
                    dtd.resolve({
                        start: data.startDate,
                        end: data.endDate
                    });
                } else {
                    dtd.resolve(null);
                }
            }, function() {
                dtd.resolve(null);
            });
            return dtd.promise();
        },
        getData: function(url, params) {
            var dtd = $.Deferred();
            ajax.run(url, params, function(data) {
                //alert(JSON.stringify(data));
                try {
                    var json = _dataJson = JSON.parse(data.BINDATA);
                    var flag = json.code,
                        mes = json.msg,
                        isReady = json.data.isReady;
                    if (flag === "0") {
                        dtd.resolve(json.data);
                       
                    } else {
                        alert(mes);
                        $('.onput').hide();
                        $('.main').hide();
                        $('body').addClass('empty json');
                        $('.empty .foot').css('background-color','#fff').html('');
                        //dtd.resolve();
                    }
                    //$('.onput').hide();
                } catch (e) {
                    //$('.onput').hide();
                    /*$('.main').hide();
                    $('body').addClass('empty active');*/
                }
                if(isReady!=1){
                    $('.main').hide();
                    $('body').addClass('empty');
                    $('.empty .foot').css('background-color','rgb(240, 239, 244)').html('<span>【风险揭示】</span>由于时间跨度、手续费、个别业务特殊性原因，可能导致盈亏金额、买卖均价等计算误差，以上数据仅供参考，最终以实际交割单为准。');
                }
            }, function(xml) {
                $('.onput').hide();
                dtd.reject();
                xml.ERRORMESSAGE && alert("网络异常");
                $('.main').hide();
                $('body').addClass('empty json');
                $('.empty .foot').css('background-color','#fff').html('');
            });
            return dtd.promise();
        },
        innerDom: function(json) {
            //alert(json.baseInfo.stockName);
            if (json && json.baseInfo.stockName && json.baseInfo.stockCode) {
                $('.main').show();
                $('body').removeClass('empty');
                var tpNav = _.template($("#navJson").html()),
                    tpList = _.template($("#tapList").html());
                json.tradeInfo.unitYuan = params.CURRENCYTEXT;
                //alert(JSON.stringify(json.baseInfo));
                params.MARKETNU = json.baseInfo.marketType === "1" ? "2A01" : "1A0001"
                json.baseInfo.rq = base.getUrlParameter('isFouse')
                $('section.nav').html(tpNav({
                    data: json.baseInfo,
                }));
                json.tradeInfo.tradeNum = json.baseInfo.tradeNum;
                json.tradeInfo.CodeName = params.NAME;
                json.tradeInfo.totalNum = json.baseInfo.optCycle;
                $('.changeVale').html(params.NAME);
                $('section.kList').html(tpList({
                    data: json.tradeInfo,
                }));
                if (!(json.tradeInfo.zlist && json.tradeInfo.zlist.length !== 0)) {
                    $('section.kList').addClass('empty');
                    $('section.kList h3').hide();
                } else {
                    $('section.kList').removeClass('empty');
                    $('section.kList h3').show();
                }
            } else {
                $('.main').hide();
                $('body').addClass('empty');
                $('.empty .foot').css('background-color','rgb(240, 239, 244)').html('<span>【风险揭示】</span>由于时间跨度、手续费、个别业务特殊性原因，可能导致盈亏金额、买卖均价等计算误差，以上数据仅供参考，最终以实际交割单为准。');
            }
            if(json.tradeInfo.totalNum==0){
                 $('section.canvasText h3').html('【我的操作分析】 <span>期间对'+params.NAME +'未进行买卖操作').addClass('empty');
            }else{
                $('section.canvasText h3').html('【我的操作分析】 <span>期间对'+params.NAME +'进行了' + json.tradeInfo.totalNum + '个持仓周期的买卖操作，共交易' + json.tradeInfo.tradeNum + '次' + '</span>' + '<span class="link"></span>');
            }
            /*$('.onput').hide();
            params.kList1 =kDateList1= dataKList;
            pageObj.drawK(dataKList);*/

             getKData(params.CODE, '', params.MAXSTART.replace(/\//g, '-'), params.MAXEND.replace(/\//g, '-'), function(_json) {
                 //alert(params.MAXSTART);
                $('.onput').hide();
                 if (_json.list.length == 0) {
                     $('.canvasText,.k,.kList').hide();
                     $('footer').addClass('empty');
                 } else {
                     $('.canvasText,.k,.kList').show();
                     params.kList1 = kDateList1 = _json;
                     pageObj.drawK(_json);
                      $('footer').removeClass('empty');
                 }
             });
             //80014报错处理
             var timeClear = setTimeout(function(){
                 timeClear = null;
                 clearTimeout(timeClear);
                if (!kDateList1) {
                    $('.canvasText,.k,.kList').hide();
                     $('footer').addClass('empty');
                    $('.onput').hide();
                } 
             },10000);
            params.json = json;
        },
        drawK: function(data) {
            _tabeJson = data.list;
            base.log(JSON.stringify(data.list));
            //alert(JSON.stringify(data.list));
            if (data.list.length == 0) {
                return;
            }
            var start = params.MAXSTART,
                len = data.list.length,
                end = params.MAXEND,
                unit = (data.max - data.min) * 0.05;
            $('#canvas canvas').remove();
            // 第一个周期出现在 可是区域
            var zq_list = (_dataJson.data.tradeInfo && _dataJson.data.tradeInfo.zlist) || [];
            parseKData(zq_list).then(function(dataList){
                // 第一个周期出现在 可是区域
                if(dataList.length==0){
                    return false;
                }
                var zq_item = dataList[dataList.length-1],
                    dataIndex = 0;
                gbDataIndex = 0;
                if(gbDataIndex==0&&zq_item[0]&&zq_item[1]&&zq_item[3]&&zq_item[2]){
                    gbDataIndex = chart.dataIndex;
                    if(zq_item[2]-params.DEFAULTSIZE>=0){
                        gbDataIndex=zq_item[3] - params.DEFAULTSIZE+1;
                    }
                } 
            });
            KChartOne = new chart({
                dom: "#canvas",
                grid: {
                    yGridLine: [false, true, true, false],
                    yLineStyle:{
                        lineWidth:'0.5',
                        strokeStyle:'rgba(224,224,224,.5)'
                    }
                },
                dataIndex: gbDataIndex,
                defaultDataSize: params.DEFAULTSIZE,
                drag: true,
                scale: 1.2,
                series: [{
                    type: 'K',
                    min: data.min,
                    max: data.max,
                    data: data.list,
                    columnWidth: '80%',
                    global: _dataJson.data.buySellList,
                    maskList: [
                        { min: end.replace(/\-|\//g, ''), max: data.list[data.list.length - 1][0].replace(/\-|\//g, ''), maxWidth: true }
                    ]
                }, ],
                events: {
                    touchstart: objEvent.start,
                    touchmove: objEvent.move,
                    touchend: function(){
                        base.log('end');
                    },
                    canvasChangeStart:objEvent.end,
                    canvasChange: function(x, chart) {
                        if ($('section.canvasText .canvasClick').hasClass('active')) {
                            KChartTwo && KChartTwo.upDateCanvas(x, chart.dataIndex);
                        }
                        drawDialogReact(chart, data._startdate);
                        gbDataIndex = chart.dataIndex;
                        //objEvent.dialogText();
                    },
                    canvasChangeEnd: function(chart) {
                        gbDataIndex = chart.dataIndex;
                        //objEvent.dialogText();
                        //objEvent.end();
                    }
                },
                flexible: {
                    left: 0,
                    top: 10,
                    right: 0,
                    bottom: 16,
                    right: 0
                },
                xAxis: {
                    data: [{ label: data.list[0][0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'), textStyle: { fillStyle: '#979797'} }, { label: end.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'), textStyle: { fillStyle: 'transparent' } }],
                    // formatter:function(value){
                    margin: [12 , 5],
                    alignment: "justify",
                    lineStyle:{
                        lineWidth:'0.5', 
                        strokeStyle:'rgba(224,224,224,0.5)'
                    },
                    textStyle: {
                        font: '12px PingFangSC-Regular',
                    }
                    // }
                },
                yAxis: {
                    show: false,
                    avgNum: 1,
                    labelAlign: 'inside',
                    basisPoint: false,
                    textStyle: {
                        font: '10px PingFangSC-Regular',
                        fillStyle: 'transparent'
                    },
                    margin: 5,
                    formatter: function(value) {
                        return value.toFixed(2)
                    }
                }

            });
            $('#max').html(data.max);
            $('#min').html(data.min);
            GBKStartDate = data._startdate;
            setTimeout(function() {
                drawDialogReact(KChartOne, data._startdate);
            }, 10);
            //K线右下角显示滑动查看
            if(data.list.length>params.DEFAULTSIZE){
                $(".main .k .more-txt").show();
            }else{
                $(".main .k .more-txt").hide();
            }
        },
        pageEvent: function() {
            //买卖均价说明
            $('.main .canvasText').on('click', 'h3 span.link', function() {
                var popup = new Popup({
                    // attached: "#scroll",s
                    id: "my-pop",
                    btnNo: 1,
                    bgColor:"#FFFFFF",
                    title: "买卖均价说明",
                    content: "<div>选择分析周期后，可能出现在起始日期之前，已持有该股票的情况。对此，将以起始日期前一交易日的收盘价作为买入均价进行盈亏计算。</div><div>选择分析周期后，也可能出现在结束日期之后，依旧持有该股票的情况。对此，将以结束日期的收盘价作为卖出均价进行盈亏计算。</div><div class='tips'>（买卖均价中已包含手续费）</div>",    
                    ok: "确定",
                    // cancel: "立即升级",
                    align: "center"
                });
                $(".popup .button.cancel").on("click", function() {

                });
                //阻止原生事件
                $(".popup-cover").on('touchmove', function(event) {
                    event.preventDefault();
                });
                $(".popup").on("touchmove", function(e) {
                    e.preventDefault();
                });
            }); 
            //跳转个股行情
            $('.main .nav').on('click', 'h1', function() {
                base.log(params.CODE);
                base.href(base.stockURL("http://stock:"+params.CODE));
            }); 
            //时间显示click
            $('header ').on('click', '.panel-body dd', function() {
                var _self = $(this).parent(),
                    img = _self.find('img');
                //alert(_self.hasClass('active'));
                if (_self.hasClass('active')) {
                    _self.removeClass('active');
                    img.attr('src', params.DOWNIMG);
                } else {
                    _self.addClass('active');
                    img.attr('src', params.UPIMG);
                }
                return false;
            });
            //时间选择click
            $('.dropdown-menu').on('click', 'li', function(e) {
                var _self = $(this).parent().parent(),
                    img = _self.find('img'),
                    _type = $(this).attr('data-id').trim();
                params.listTime = $(this).attr('data-time').replace(/\s/g, '').split("-");
                if (_self.hasClass('active')) {
                    _self.removeClass('active');
                    img.attr('src', params.DOWNIMG);
                } else {
                    _self.addClass('active');
                    img.attr('src', params.UPIMG);
                }
                if (params.listTime.length > 1 && !$(this).hasClass('active')) {
                    $('.onput').css('background-color', 'transparent').show();
                    params.DATEDOM.html($(this).attr('data-html'));
                    kDateList1 = null;
                    params.DATETYPE = _type;
                    pageObj.getData(params.URL, {
                        dateType: _type,
                        startDate: params.listTime[0],
                        endDate: params.listTime[1],
                    }).then(pageObj.innerDom);
                    params.MAXSTART = params.listTime[0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');
                    params.MAXEND = params.listTime[1].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');
                    $('#canvas .line').removeClass('l2');
                    $('section.canvasText .canvasClick').html(params.BTNACTIVE).removeClass('active');
                    $('#canvas2').hide();
                    $('#canvas .line,#canvas2 .line').hide();
                    $('#canvas2 canvas').remove();
                    $('#canvas .bluearr,#canvas .orangearr').remove();
                    TalkingData.onHTSCEvent("page", "leaf304", "持仓股综合分析_个股交易分析." + params.NAME, "", "选择日期");
                } else if (params.listTime.length == 1) {
                    $('#canvas .line').removeClass('l2');
                    $('section.canvasText .canvasClick').html(params.BTNACTIVE).removeClass('active');
                    $('#canvas2').hide();
                    $('#canvas .line,#canvas2 .line').hide();
                    $('#canvas2 canvas').remove();
                    $('#canvas .bluearr,#canvas .orangearr').remove();
                    base.href('http://action:10061/?type=9&&topcolor=F64843&&fullscreen=1&&url=/zlcftajax/information/position/custom-time.htm?beginTime=' + params.MAXSTART + '&endTime=' + params.MAXEND + '&=' + '&stockCode=' + base.getUrlParameter('stockCode') + '&marketCode=' + base.getUrlParameter('marketCode') + '&currency=' + params.CURRENCY + '&source=' + params.SOURCE + "&type=1");
                }
                clickTwoKIndex++;
                $(this).addClass('active').siblings().removeClass('active');
                return false;
            });
            //canvas 显示click
            $('section.canvasText .canvasClick').click(function() {
                var _self = $(this);
                if (_self.hasClass('active')) {
                    $('#canvas .line').removeClass('l2');
                    _self.html(params.BTNACTIVE).removeClass('active');
                    $('#canvas2').hide();
                    $('#canvas .line,#canvas2 .line').hide();
                    $('#canvas2 canvas').remove();
                    //$('#canvas .bluearr,#canvas .orangearr').remove();
                } else {
                    $('#canvas .line').addClass('l2');
                    _self.html(params.BTNTEXT).addClass('active');
                    $('#canvas2').show().addClass('loading');
                    // 上 1A0001 深 2A01
                    var str = params.MARKETNU === "1A0001" ? '上证指数' : "深证指数";
                    $('#canvas2').attr('data-value', str);
                    /*params.kList2 = dataKList;
                    drawCanvas(params.kList2);
                    $('#canvas2').removeClass('loading');*/

                     getKData(params.CODE, params.MARKETNU, params.MAXSTART.replace(/\//g, '-'), params.MAXEND.replace(/\//g, '-'), function(_json) {
                         params.kList2 = _json;
                         drawCanvas(params.kList2);

                         $('#canvas2').removeClass('loading');
                     });

                }
                return false;
            });
            //跳转到分析
            $('.kList').on('click', '.container', function() {
                var statu = $(this).attr('data-statue'); 
                if(statu!=='false'){
                    return false;
                }
                var pDate = $(this).attr('data-time').trim().replace(/\s/ig, '').split("-"),
                    _start = 20 + pDate[0],
                    _end = 20 + pDate[1],
                    mone = $(this).find('.col-xs-12 span:last-child').html(),
                    zInedx = $(this).attr('data-index'); //.replace(/\D+/, '');
                    _start = _start.replace(/\./g,'/');
                    _end = _end.replace(/\./g,'');
                if (mone.indexOf('+') > 0 || mone.indexOf('--') > 0) {
                    mone = '盈利' + mone.replace(/(\\u4e00-\\u9fa5)+|\s/, '');
                } else {
                    mone = '亏损' + mone.replace(/(\\u4e00-\\u9fa5)+|\s/, '');
                }
                TalkingData.onHTSCEvent("click", "leaf304", "持仓股综合分析_个股交易分析." + params.NAME, "", "个股买卖点明细|pos=" + $(this).attr('data-index') + "|time=" + $(this).find('p').html());
                base.href('http://action:10061/?type=9&&topcolor=F64843&&fullscreen=1&&url=/zlcftajax/information/position/business-point.htm?kLineEndDate=' + params.MAXEND +'&zIndex='+zInedx+ '&kLineStartDate=' + params.MAXSTART + '&startDate=' + encodeURIComponent(_start + '&endDate=' + _end + '&stockName=' + params.NAME + '&stockCode=' + params.CODE + '&payoff=' + mone + '&marketCode=' + params.MAKKETCODE + '&dateType=' + params.DATETYPE + '&source=' + params.SOURCE + '&trueStartDate=' +$(this).attr('data-truestartdate') + '&trueEndDate=' + $(this).attr('data-trueenddate')+'&trueCenter='+$(this).attr('data-truecenter')+'&trueIndexStart='+$(this).attr('data-trueindexstart')+'&trueIndexend='+$(this).attr('data-trueindexend')+'&dataType='+params.DATETYPE));
                return false;
            });
            $('body').click(function() {
                $('.panel-body').removeClass('active').find('img').attr('src', 'images/arrow-0.png');
            });
        }
    };

    function drawCanvas(data) {
        console.log('2:' + gbDataIndex);
        if (!data || data.length == 0) {
            return;
        }
        var start = params.MAXSTART,
            len = data.list.length,
            end = params.MAXEND,
            unit = (data.max - data.min) * 0.05;
        $('#canvas2 canvas').remove();
        base.log(JSON.stringify(data.list));
        // 
        KChartTwo = new chart({
            dom: "#canvas2",
            grid: {
                yGridLine: [false, true, true, false],
                yLineStyle:{
                        lineWidth:'0.5', 
                        strokeStyle:'rgba(224,224,224,0.5)'
                    }
            },
            dataIndex: gbDataIndex,
            scale: 1.06,
            series: [{
                    type: 'K',
                    min: data.min,
                    max: data.max,
                    data: data.list,
                    columnWidth: '80%',
                    maskList: [
                        { min: end.replace(/\-|\//g, ''), max: data.list[data.list.length - 1][0].replace(/\-|\//g, ''), maxWidth: true }
                    ]
                },

            ],
            defaultDataSize: params.DEFAULTSIZE,
            drag: true,
            events: {
                touchstart: objEvent.start,
                touchmove: objEvent.move,
                touchend: function(){},
                canvasChangeStart:objEvent.end,
                canvasChange: function(x, chart) {
                    KChartOne.upDateCanvas(x, chart.dataIndex);
                    drawDialogReact(KChartOne, GBKStartDate);
                    //objEvent.dialogText();
                    objEvent.end();
                },
                canvasChangeEnd: function(chart) {
                    gbDataIndex = chart.dataIndex;
                    objEvent.dialogText();
                }
            },
            flexible: {
                left: 0,
                top: 20,
                right: 0,
                bottom: 16,
                right: 0
            },
            xAxis: {
                data: [{ label: data.list[0][0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'), textStyle: { fillStyle: '#979797' } }, { label: end.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'), textStyle: { fillStyle: 'transparent' } }],
                // formatter:function(value){
                margin: [12, 5],
                alignment: "justify",
                lineStyle:{
                        lineWidth:'0.5', 
                        strokeStyle:'rgba(224,224,224,0.5)'
                    },
                textStyle: {
                    font: '12px PingFangSC-Regular',
                }
                // }
            },
            yAxis: {
                show: false,
                avgNum: 1,
                labelAlign: 'inside',
                basisPoint: false,
                textStyle: {
                    font: '10px PingFangSC-Regular',
                    fillStyle: '#797979'
                },
                margin: 5,
                formatter: function(value) {
                    return value.toFixed(2)
                }
            }

        });
        /*
                setTimeout(function() {
                    drawDialogReactThree(KChartOne, GBKStartDate);
                }, 0);*/
    }
    var objEvent = {
        index:0,//k线位置
        width: $('#canvas').width(),
        line: document.querySelector("#canvas .line"),
        lineStyle1: document.querySelector("#canvas .line").style,
        lineStyle2: document.querySelector("#canvas2 .line").style,
        lineTest: document.querySelector("#canvas .line .test"),
        lineSpan: document.querySelector("#canvas2 .line span"),
        canvasFirst: document.querySelector("#canvas canvas"),
        canvasTwo: document.querySelector("#canvas2 canvas"),
        start: function(x) {
            objEvent.lineStyle1.display = 'none';
            objEvent.lineStyle2.display = 'none';
            objEvent.dialog(x);
        },
        move: function(x) {
            objEvent.dialog(x);
        },
        end: function(x) {
            objEvent.lineStyle1.display = 'none';
            objEvent.lineStyle2.display = 'none';
        },
        dialog: function(x) {
            var show = $('section.canvasText .canvasClick').hasClass('active');
            if (!show) {
                return;
            }
            var arr1 = document.querySelector("#canvas canvas"),
                arr2 = document.querySelector("#canvas2 canvas");
            var attr1 = arr1.getAttribute("data-points"),
                attr2 = arr2.getAttribute("data-points");
            var _selfStart = 0,
                _selfEnd = 0;
            attr1 = JSON.parse(attr1);
            attr2 = JSON.parse(attr2);
            if (!attr1[x.index] || !attr2[x.index]) {
                return;
            }
            if (GBKStartDate && x.index >= GBKStartDate) {
                return;
            }
            
            objEvent.lineStyle1.display = 'block';
            
            if(base.isIOS()){
                objEvent.lineStyle1.left = (Math.ceil(attr1[x.index].x)-1) + "px";
                objEvent.lineStyle2.left = (Math.ceil(attr1[x.index].x)-1) + "px";
            }else{
                objEvent.lineStyle1.left = Math.ceil(attr1[x.index].x) + "px";
                objEvent.lineStyle2.left = Math.ceil(attr1[x.index].x) + "px";
            }
            //objEvent.lineStyle2.display = 'block';

            var t1 = Math.abs(attr1[x.index].open - 0 - attr1[x.index].close) / 2,
                t2 = Math.abs(attr2[x.index].open - 0 - attr2[x.index].close) / 2;
            if (attr1[x.index].open >= attr1[x.index].close) {
                t1 = attr1[x.index].close + t1;
                t2 = attr2[x.index].close + t2;
            } else {
                t1 = attr1[x.index].open + t1;
                t2 = attr2[x.index].open + t2;
            }
            if ($('#canvas').width() - x.value * 2 > 0) {
                objEvent.lineTest.className = 'test';
            } else {
                objEvent.lineTest.className = 'test right';
            }
            objEvent.lineTest.style.marginTop = (t1 - 10) + 'px';
            objEvent.lineSpan.style.top = (t2 + 5) + 'px';
            objEvent.index = x.index;
            objEvent.dialogText();
        },
        dialogText:function(){
            var str = params.MARKETNU === "1A0001" ? '上证指数' : "深证指数";
            var index = objEvent.index,
                marketIndex =  Number(params.kList2.list[index + gbDataIndex][2])?Number(params.kList2.list[index + gbDataIndex][2]).toFixed(2):'--';
            $(objEvent.lineTest).find('p').eq(0).html(params.kList2.list[index + gbDataIndex][0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3'));
            $(objEvent.lineTest).find('p').eq(1).html('收盘价：<span style="font-family:PingFangSc-Medium">' + Number(params.kList1.list[index + gbDataIndex][2]).toFixed(2) + '' + params.CURRENCYTEXT + '</span>');
            $(objEvent.lineTest).find('p').eq(2).html(str+'：<span style="font-family:PingFangSc-Medium">' + marketIndex + '</span>');
        }
    };
    pageObj.init();
    window.GoBackOnLoad = function() {
        local.read({
                P_SOURCE: "", //系统源 150001 普通 150     002 信用  150003 限售股 150000 全账户
                P_CURRENCY: "", //401156 人民币 401344  港元 401840 美元
                P_DATETYPE: "", // 01 近一个月 03 近三个月 06 近六个月 00 自定义时间段
                P_MARKETTYPE: "", //市场类型 0 上证 1 深圳           
                P_STARTDATE: "", //开始时间
                P_ENDDATE: "", //结束时间
                P_DATELIST: "",
                P_ACCOUNT:'',
            }, function(_obj) {
                params.SOURCE = base.getUrlParameter('source');
                params.CURRENCY = base.getUrlParameter('currency');
                /*params.SOURCE = _obj.P_SOURCE;
                params.CURRENCY = _obj.P_CURRENCY;*/
                params.CURRENCYTEXT = _obj.P_CURRENCY;
                //params.DATETYPE = _obj.P_DATETYPE;
                /*params.MAXSTART = _obj.P_STARTDATE.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');
                params.MAXEND = _obj.P_ENDDATE.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3');*/
                params.URL = '/reqxml?action=27401&path=/account/hold_analysis/single_stock_explain?clientNo='+_obj.P_ACCOUNT+'&token=($token)&stockCode=' + base.getUrlParameter('stockCode') + '&marketCode=' + base.getUrlParameter('marketCode') + '&currency=' + params.CURRENCY + '&source=' + params.SOURCE;
                //var tpNav = _.template($("#headerJson").html());
                $('#canvas .line').removeClass('l2');
                $('section.canvasText .canvasClick').html(params.BTNACTIVE).removeClass('active');
                $('#canvas2').hide();
                $('#canvas .line,#canvas2 .line').hide();
                $('#canvas2 canvas').remove();
                pageObj.readFile().then(function(obj) {
                    var _params = {};
                    if (obj) {
                        params.DATEDOM.html(obj.start.replace('20', '') + '-' + obj.end.replace('20', ''));
                        _params = {
                            dateType: '00',
                            startDate: obj.start.replace(/\//ig, ''),
                            endDate: obj.end.replace(/\//ig, '')
                        };
                        $('header .dropdown-menu li').eq(3).addClass('active');
                        params.MAXSTART = obj.start;
                        params.MAXEND = obj.end;
                        params.DATETYPE = '00';
                        kDateList1 = null;
                        //alert(params.MAXSTART);
                        file.insert("positon.js", { startDate: null, endDate: null }, function(data) {
                            pageObj.getData(params.URL, _params).then(pageObj.innerDom);
                        });
                    }
                    

                });
            });
    };

    function drawDialogReactThree(chart, flagDate) {
        var ctx = chart.ctx,
            width = chart.width,
            height = chart.height,
            list = (_dataJson.data.tradeInfo && _dataJson.data.tradeInfo.zlist) || [],
            zhlist = [],
            checked = [],
            arr = document.querySelector("#canvas canvas"),
            attr = arr.getAttribute("data-points"),
            unit = width / params.DEFAULTSIZE;
        attr = JSON.parse(attr);
        if (flagDate) {
            checked = [unit * flagDate, width];
        }
        if (KChartTwo) {
            KChartTwo.ctx.beginPath();
            KChartTwo.ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
            KChartTwo.ctx.rect(checked[0], 1, (checked[1] - checked[0]), height);
            KChartTwo.ctx.fill();
        }
    }

    function drawDialogReact(chart, flagDate) {
        var ctx = chart.ctx,
            width = chart.width,
            height = chart.height,
            list = (_dataJson.data.tradeInfo && _dataJson.data.tradeInfo.zlist) || [],
            zhlist = [],
            checked = [],
            arr = document.querySelector("#canvas canvas"),
            attr = arr.getAttribute("data-points"),
            attr_str = params.kList1.list.join(''),
            unit = width / params.DEFAULTSIZE,
            parentIndex = 0;
        attr = JSON.parse(attr);
        parseKData(list).then(function(dataList) {
            if(dataList.length==0){
                return false;
            }
            _.each(dataList, function(_item) {
                if(!_item[0]||!_item[1]){
                    return false;
                }
                var scItem = [],
                    _index = 0,
                    len = attr.length,
                    startSelf = new Date(_item[0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                    endSelf = new Date(_item[1].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                    attr_end = new Date(attr[len - 1].date.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                    attr_start = new Date(attr[0].date.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime();
                if (startSelf < attr_start) {
                    scItem[0] = 1;
                    scItem[2] = 1;
                }
                if (endSelf > attr_end) {
                    scItem[1] = width;
                    scItem[3] = 1;
                }
                _.each(attr, function(item) {
                    var _date = item.date.replace(/(\/)|(\s)|(\-)/g, ''),
                        _dataTime = new Date(_date.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime();
                    if (_item[0] === _date && attr[_index]) {
                        scItem[0] = attr[_index].x;
                    }
                    if (_item[1] === _date && attr[_index]) {
                        scItem[1] = attr[_index].x;
                    }
                    if (_item[4] === _date && attr[_index]) {
                        scItem[4] = attr[_index].x;
                        if (!_item[5]) {
                            scItem[4] = attr[_index].x-unit/2;
                        }
                    }

                    _index++;
                });
                if (scItem.length > 1) {
                    zhlist.push(scItem);
                }
            });
           
            
        });

        var textIndex = 1;
        zhlist = zhlist.reverse();
        _.each(zhlist, function(_item) {
            var minX = (_item[1] == _item[0]) ? 1 : (_item[1] - _item[0]);
            ctx.beginPath();
            if (_item[1] !== _item[0]) {
                ctx.lineWidth = "0.5";
                ctx.strokeStyle = "#FF8400";
                ctx.fillStyle = "rgba(251,164,87,0.20)";
                drawReact(ctx, _item[0], 1, minX, height - 17, _item);
                ctx.rect(_item[0], 1, minX, height - 17);
                ctx.fill();
            } else {
                drawDashedLine(ctx, _item[0], 1, _item[0], height - 16, '#FF8400', '0.5', '2');
            }
            ctx.restore();
            if (_item[4]) {
                ctx.font = "13px PingFangSC-Medium";
                ctx.textAlign = "center";
                ctx.lineWidth = 1;
                ctx.fillStyle = '#FF8400';
                ctx.fillText(textIndex, _item[4], height - 20);
            }
            textIndex++;
        });
        /* if (flagDate) {
             checked = [unit * flagDate, width];
             ctx.beginPath();
             ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
             ctx.rect(checked[0], 1, (checked[1] - checked[0]), height);
             ctx.fill();
         }
         if (KChartTwo) {
             KChartTwo.ctx.beginPath();
             KChartTwo.ctx.fillStyle = "rgba(255, 255, 255, 0.7)";
             KChartTwo.ctx.rect(checked[0], 1, (checked[1] - checked[0]), height);
             KChartTwo.ctx.fill();
         }*/

    }
    //虚线矩形
    function drawReact(ctx, x, y, w, h, item) {
        drawDashedLine(ctx, x, y, (x + w), y, '#FF8400', '0.5', '2');
        if (!item[3]) {
            drawDashedLine(ctx, (x + w), y, (x + w), (y + h), '#FF8400', '0.5', '2');
        }
        drawDashedLine(ctx, (x + w), (y + h), (x), (y + h), '#FF8400', '0.5', '2');
        if (!item[2]) {
            drawDashedLine(ctx, (x), (y + h), x, y, '#FF8400', '0.5', '2');
        }
    }

    function drawDashedLine(ctx, sx, sy, tx, ty, color, lineWidth, dashLen) {
        var len = cacuDis(sx, sy, tx, ty),
            lineWidth = lineWidth || 1, //虚线宽度
            dashLen = dashLen || 2, //虚线默认间隔
            num = ~~(len / dashLen); //虚线数量
        ctx.beginPath();
        for (var i = 0; i < num; i++) {
            var x = sx + (tx - sx) / num * i,
                y = sy + (ty - sy) / num * i;
            ctx[i & 1 ? "lineTo" : "moveTo"](x, y);
        }
        ctx.closePath();
        ctx.lineWidth = lineWidth; //配置线条宽度
        ctx.strokeStyle = color; //配置线条颜色
        ctx.stroke(); //闭合线
    }

    function cacuDis(sx, sy, tx, ty) {
        return Math.sqrt(Math.pow(tx - sx, 2) + Math.pow(ty - sy, 2));
    }
    /**
     * 解析k线数据
     */
    function parseKData(data) {
        var dtd = $.Deferred(),
            list = [],
            _list = data.list,
            buyList = (_dataJson.data.tradeInfo && _dataJson.data.tradeInfo.zlist) || [],
            buy_len = buyList.length;
        /* if (_list.length <= 0) {
             return;
         }*/
        _.each(buyList, function(item) {
            if (params.kList1.list.length < 0||!item.startDateParam||!item.endDateParam) {
                return;
            }
            var scItem = [],
                _index = 0,
                _centerIndex,
                len = params.kList1.list.length,
                startSelf = new Date(item.startDateParam.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                endSelf = new Date(item.endDateParam.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                _dataKStart = new Date(params.kList1.list[0][0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                _dateKEnd = new Date(params.kList1.list[len - 1][0].replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                listStr = params.kList1.list.join('');
            if (startSelf < _dataKStart) {
                scItem[0] = params.kList1.list[0][0];
                scItem[2] = 0;
            }
            if (endSelf > _dateKEnd) {
                var centerpoit = parseInt((len - 1) / 2,10);
                scItem[1] = params.kList1.list[len - 1][0];
                _centerIndex = params.kList1.list[centerpoit][0];
                scItem[4] = _centerIndex;
                scItem[3] = len - 1;
                scItem[5] = isInteger((len - 1) / 2);
            }
            if(startSelf < _dataKStart&&endSelf<_dataKStart){
                return;
            }
            _.each(params.kList1.list, function(_item) {
                var _date = _item[0].replace(/(\/)|(\s)|(\-)/g, ''),
                    _dataTime = new Date(_date.replace(/(\d{4})(\d{2})(\d{2})/g, '$1/$2/$3')).getTime(),
                    center = 0;
                if (startSelf === _dataTime) {
                    scItem[0] = _item[0];
                    scItem[2] = _index;
                    if(scItem[1]){
                        var center = parseInt((scItem[3] - _index) / 2,10);
                        scItem[4] = params.kList1.list[scItem[3] - center][0];
                        scItem[5] = isInteger((scItem[3] - _index) / 2);   
                    }
                }
                if (endSelf === _dataTime) {
                    scItem[1] = _item[0];
                    scItem[3] = _index;
                    center = parseInt((_index - scItem[2]) / 2,10);
                    //alert(center);
                    scItem[4] = params.kList1.list[_index - center][0];
                    //alert(scItem[4]);
                    scItem[5] = isInteger((_index - scItem[2]) / 2);
                    //alert(scItem[5]);
                }
                if (!scItem[0] && startSelf >= new Date(params.MAXSTART).getTime() && startSelf < new Date(params.MAXEND).getTime() && listStr.indexOf(_item.startDateParam) < 0 && startSelf < _dataTime) {
                    scItem[0] = params.kList1.list[_index][0];
                    scItem[2] = _index;
                    if(scItem[1]){
                        var center = parseInt((scItem[3] - _index) / 2,10);
                        scItem[4] = params.kList1.list[scItem[3] - center][0];
                        scItem[5] = isInteger((scItem[3] - _index) / 2);  
                    }

                }
                if (!scItem[1] && endSelf <= new Date(params.MAXEND).getTime() && listStr.indexOf(_item.endDateParam) < 0 && endSelf < _dataTime) {
                    var indexSelf = _index - 1<0?0:_index - 1;
                    scItem[1] = params.kList1.list[indexSelf][0];
                    scItem[3] = indexSelf;
                    center = parseInt((_index - scItem[2]-1) / 2,10);
                    if(_index == scItem[2]){
                        scItem[4] = params.kList1.list[_index - center][0];
                        //scItem[5] = isInteger((0) / 2);
                    }else{
                        scItem[4] = params.kList1.list[_index - center - 1][0];
                        
                    }
                    scItem[5] = isInteger((_index - scItem[2]-1) / 2);
                    if(_index == 0){
                        scItem[5] = true;
                    }
                }
                _index++;
            });
            if (scItem.length > 1) {
                list.push(scItem);
            }
        });
        dtd.resolve(list);
        var indexTrue = 0;
        _.each(list,function(_item){
            $('.container').eq(indexTrue).attr({
                "data-trueStartDate":_item[0],
                "data-trueEndDate":_item[1],
                'data-trueCenter':_item[4],
                'data-trueIndexstart':_item[2],
                'data-trueIndexend':_item[3]
            });
            indexTrue++;
        });
        return dtd.promise();
    }

    function isInteger(obj) {
        return obj % 1 === 0;
    }
    //1A0001
    function getKData(code, marketCode, start, end, fn) {
        //alert(start);
        var _code = code;
        if (marketCode) {
            _code = marketCode
        }
        var range = 500;
        if(params.DATETYPE == '01'){
            range = 100;
        }else if(params.DATETYPE == '03'){
            range = 200;
        }else if(params.DATETYPE == '06'){
            range = 500;
        }
        /*_code = '184721';*/
        base.href("http://action:80014/?stockcode=" + _code + "&&daterange="+range+"&&jsfuncname=KdateFn&&jsfailfunc=kDateFnFail");
        window.kDateFnFail = function() {
            fn && fn({
                list: [],
                max: 0,
                min: 0,
            });
        }
        window.KdateFn = function(data) {
            var tm = typeof(data) == "object" ? data : JSON.parse(data),
                _list = tm.list,
                _list_self = [],
                _index = 0,
                _flag = 1,
                _startdate = null;
            //console.log(JSON.stringify(tm));
            _list = _.filter(_list, function(value) {
                var _start = new Date(start).getTime(),
                    _end = new Date(end).getTime(),
                    _time = new Date(value[0]).getTime(),
                    _result = [];
                if ((kDateList1 && _time >= _start && _index <= 1000) || ((_time >= _start && _index < params.DEFAULTSIZE) || (_index >= params.DEFAULTSIZE && _time <= _end))) {
                    _index++;
                    if (_time > _end && !kDateList1) {
                        if (_flag == 1) {
                            _startdate = _index - 1;
                        }
                        _flag++;
                    }
                    _result[0] = value[0];
                    _result[1] = value[2];
                    _result[2] = value[1];
                    _result[3] = value[3];
                    _result[4] = value[4];
                }
                return _result.length > 0;
            });
            if (kDateList1) {
               /*var listStr = kDateList1.list.toString();
                _.each(_list, function(value) {
                    if (listStr.indexOf(value[0].replace(/\-/g, '')) >= 0) {
                        _list_self.push([value[0].replace(/\-/g, ''), value[3], value[4], value[2], value[1]]);
                    }
                });*/
                for(var i = 0,len=_list.length;i<len;i++){
                    var valueStr =_list[i][0].replace(/\-/g, ''),
                    value = _list[i];
                    for(var j = 0,jlen = kDateList1.list.length;j<jlen;j++){
                        if(valueStr===kDateList1.list[j][0]){
                            _list_self[j]=[value[0].replace(/\-/g, ''),value[3] , value[4], value[2], value[1]];
                            break;
                        }else if(!_list_self[j]){
                             _list_self[j]=[kDateList1.list[j][0], null,null, null, null];
                        }

                    }
                  }
            } else {
                _.each(_list, function(value) {
                    _list_self.push([value[0].replace(/\-/g, ''), value[3], value[4], value[2], value[1]]);

                });

            }
            if (_list_self.length == 0) {
                fn && fn({
                    list: [],
                    max: 0,
                    min: 0,
                });
            } else {
                var list_max = [],list_min = [];
                for(var i=0;i<_list_self.length;i++){
                    if(_list_self[i][3]!=null&&_list_self[i][4]!=null){
                        var max_min =[Number(_list_self[i][1]),Number(_list_self[i][2]),Number(_list_self[i][3]),Number(_list_self[i][4])];
                        list_max.push(Math.max.apply(null, max_min));
                        list_min.push(Math.min.apply(null, max_min));

                    }
                }
                var max = Math.max.apply(null, list_max);
                var min = Math.min.apply(null, list_min);
                fn && fn({
                    list: _list_self,
                    max:max,
                    min:min,
                    _startdate: _startdate
                });
            }
        }
    }

});